import yaml
from pathlib import Path

p = Path('11-try-render.yml')
A = yaml.safe_load(p.read_text(encoding='utf-8'))
A


# gl.DUT1.CheckCommand('hi',
#                 cmd='''display ip routing-table''',
#                 expect=['255.255.255.255/32 Direct  0   0           127.0.0.1       InLoop0'],
#                 failed_assist=['🦜: hi'],
#                 stop_max_attempt=1,
#                 wait_fixed=1)

# 1. replace the right id
def replace_id(i):
    M = {'N' : 'gl.DUT'}            # the replacement map
    for k in M:
        if i.startswith(k):
            return M[k] + i.removeprefix(k)
    raise ValueError(f"Invalid ID: {i}")

# 1. replace id

import textwrap
def build_code(i : str, label: str, cmd: str, expect: list[str] = None, expect_no: list[str] = None):
    i = replace_id(i)
    if not id:
        raise ValueError(f"Invalid ID: {i}")

    cmd = cmd.strip()
    a = [f"{label!r}",
        f"cmd='''{cmd}'''",
        f"expect={expect!r}" if expect else "",
        f"not_expect={expect_no!r}" if expect_no else "",
        "stop_max_attempt=1",
        "wait_fixed=1"]
    a = [x for x in a if x]  # remove empty strings
    T = '{i}.CheckCommand({a})'
    # Format the string with the provided id, label, and cmd
    return textwrap.indent(T.format(i=i, a=',\n     '.join(a)), ' ' * 8)  # indent with 8 spaces

a = A[0]
print(build_code(i=a['id'], label=a['label'], cmd=a['cmd'], expect=a.get('expect'), expect_no=a.get('expect_no')))



# --------------------------------------------------
# real run
s0 = Path('11-before-render.txt').read_text(encoding='utf-8')
l = []
for a in A:
    try:
        s = build_code(i=a['id'], label=a['label'], cmd=a['cmd'], expect=a.get('expect'), expect_no=a.get('expect_no'))
        l.append(s)
    except ValueError as e:
        print(f"Error processing {a['id']}: {e}")
s = '\n'.join(l)
p1 = Path('test_o.py')
p1.write_text(s0 + s, encoding='utf-8')
